package servlet;

import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class UserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
       String userName=  req.getParameter("userName");
       String password = req.getParameter("password");
       // 1. 判断 用户名和密码是否为空
       if(userName == null || password==null || userName.length()==0 ||password.length()==0){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("你输入的用户名或密码为空");
            return;
        }
       // 2. 判断用户名和密码是否正确 ;
        UserDao userDao = new UserDao();
       User user = userDao.getUserByName(userName);
       if(user == null || !password.equals(user.getPassword())) {
           resp.setContentType("text/html; charset=utf8");
           resp.getWriter().write("你输入的用户名或密码不正确");
           return;
       }
        // 3. 创建会话(把查出的user对象放进去)
        HttpSession session = req.getSession(true);
         session.setAttribute("user", user );
         // 4. 跳转到页面
        resp.setStatus(302);
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         // 判断是否登录
         HttpSession session = req.getSession(false);
         if(session == null || session.getAttribute("user") == null){
             resp.setStatus(403);
             return;
         }

        // 200默认也是200 ;
         resp.setStatus(200);

    }
}
